package com.cc.ttsreader

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationManagerCompat
import java.lang.Exception

const val tag = "TTSServer"
const val NOTI_ID = 1

class TTSServer : Service() {

    var text = ""

    lateinit var tts: TextToSpeechHelper

    override fun onCreate() {
        super.onCreate()
        tts = TextToSpeechHelper(this) {
            Log.d(tag, "onCreate:tts isEnable:$it")
        }
    }

    val handler = Handler()
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val t = intent?.getStringExtra("text") ?: ""
        if (text != t) {
            text = t
            try {
                tts.speech(text) {
                    Log.d(tag, "speech end.")
                }
            } catch (e: Exception) {
                handler.postDelayed({
                    tts.speech(text) {
                        Log.d(tag, "speech end.")
                    }
                }, 2000)
            }
        }
        val noti = createNotification()
        createNotificationChannel().notify(NOTI_ID, noti)
        startForeground(NOTI_ID, noti)
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
}